//
//  GDHFaceSourceManager.m
//  GDHChatKeyBoard
//
//  Created by 高得华 on 2017/10/12.
//  Copyright © 2017年 高得华. All rights reserved.
//

#import "GDHFaceSourceManager.h"
#import "GDHFaceThemeModel.h"
#import <YYImage/YYImage.h>

//表情底部按钮图片第一个图片
static NSString *buttonToolBarEmoji = @"GDHChatKeyBoardResources.bundle/toolBarEmoji";

@implementation GDHFaceSourceManager

///从持久化存储里面加载表情源
+ (NSArray *)loadFaceSource
{
    return [GDHFaceSourceManager loadFaceSource:0];
}

///从持久化存储里面加载表情源 type:0系统 1微信
+ (NSArray *)loadFaceSource:(NSInteger)type
{
    NSMutableArray *subjectArray = [NSMutableArray array];
    NSString * zdYName = @"GDHface";///GDHfaceFz
    NSArray * sources = @[@"GDHsystemEmoji"];//@[@"GDHface", @"GDHsystemEmoji",@"GDHemotion"];
    switch (type) {
        case 0:///系统
            sources = @[@"GDHsystemEmoji"];
            break;
        case 1:///微信
            sources = @[zdYName];
            break;
        default:
            break;
    }
    
    for (int i = 0; i < sources.count; ++i)
    {
        NSString *plistName = sources[i];
        NSString *emoticonBundlePath = [[NSBundle mainBundle] pathForResource:@"GDHCKBFacePanelResources" ofType:@"bundle"];
        NSString * plistPath = [emoticonBundlePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",plistName]];//GDHface.plist
        NSDictionary * faceDic = [NSDictionary dictionaryWithContentsOfFile:plistPath];
        NSArray * allkeys = faceDic.allKeys;
        if ([plistName isEqualToString:zdYName]) {
            ///安卓到iOS的字典
            NSDictionary * and_iOSDic = [NSDictionary dictionaryWithContentsOfFile:[emoticonBundlePath stringByAppendingPathComponent:@"GDHfaceAndroid_iOS.plist"]];
            ///安卓到iOS的Keys
            NSArray * and_iOSKeys = [and_iOSDic.allKeys sortedArrayUsingComparator:^NSComparisonResult(NSString * _Nonnull obj1, NSString * _Nonnull obj2) {
                NSString * obj11 = [obj1 substringFromIndex:6];
                NSInteger o1 = [obj11 substringToIndex:obj11.length-1].integerValue;
                
                NSString * obj22 = [obj2 substringFromIndex:6];
                NSInteger o2 = [obj22 substringToIndex:obj22.length-1].integerValue;
                return o1 > o2;
            }];
            ///对应的iOS->安卓的Keys
            NSMutableArray * iOS_andKeys = [NSMutableArray new];
            for (NSString * key in and_iOSKeys) {
                [iOS_andKeys addObject:and_iOSDic[key]];
            }
            allkeys = iOS_andKeys.copy;
        }
 
        GDHFaceThemeModel *themeM = [[GDHFaceThemeModel alloc] init];
        
        if ([plistName isEqualToString:zdYName]) {
            themeM.themeStyle = GDHFaceThemeStyleCustomEmoji;
            themeM.themeDecribe = @"微信";
            themeM.themeIcon = buttonToolBarEmoji;
        }else if ([plistName isEqualToString:@"GDHsystemEmoji"]){
            themeM.themeStyle = GDHFaceThemeStyleSystemEmoji;
            themeM.themeDecribe = @"系统";
            themeM.themeIcon = buttonToolBarEmoji;
        }
        else {
            themeM.themeStyle = GDHFaceThemeStyleGif;
            themeM.themeDecribe = @"动画";
            themeM.themeIcon = @"f_static_000";
        }
        
        
        NSMutableArray *modelsArr = [NSMutableArray array];
        
        for (int i = 0; i < allkeys.count; ++i) {
            NSString *name = allkeys[i];
            GDHFaceModel *fm = [[GDHFaceModel alloc] init];
            fm.faceTitle = name;
            if (themeM.themeStyle == GDHFaceThemeStyleSystemEmoji) {
                fm.faceIcon = [faceDic objectForKey:name];
            }else{
                fm.faceIcon = [NSString stringWithFormat:@"%@/%@",emoticonBundlePath,[faceDic objectForKey:name]];
            }
            [modelsArr addObject:fm];
        }
        themeM.faceModels = modelsArr;
        
        [subjectArray addObject:themeM];
    }
    
    [GDHFaceSourceManager emoticonDic];
    return subjectArray;
}


#pragma mark - ===== 表情方面 ===== -
+ (NSBundle *)emoticonBundle {
    static NSBundle *bundle;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"GDHCKBFacePanelResources" ofType:@"bundle"];
        bundle = [NSBundle bundleWithPath:bundlePath];
    });
    return bundle;
}
/// 表情正则表达式
+ (NSRegularExpression *)regexEmoticon{
    static NSRegularExpression *regex;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{//@"\[face:\d{1,3}\]"
        regex = [NSRegularExpression regularExpressionWithPattern:@"\\[[^ \\[\\]]+?\\]" options:kNilOptions error:NULL];
    });
    return regex;
}

/// 表情字典 [表情]:地址
+ (NSDictionary *)emoticonRealDic {
    static NSMutableDictionary *dict;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *emoticonBundlePath = [[NSBundle mainBundle] pathForResource:@"GDHCKBFacePanelResources" ofType:@"bundle"];
        dict = [self _emoticonDicFromPath:emoticonBundlePath name:@"GDHface.plist"];
    });
    return dict;
}

/// iOS -> Android 表情字典
+ (NSDictionary *)emoticoniOS_AndroidDic {
    static NSDictionary *dict;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *emoticonBundlePath = [[NSBundle mainBundle] pathForResource:@"GDHCKBFacePanelResources" ofType:@"bundle"];
        dict = [NSDictionary dictionaryWithContentsOfFile:[emoticonBundlePath stringByAppendingPathComponent:@"GDHfaceiOS_Android.plist"]];
    });
    return dict;
}
/// Android -> iOS 表情字典
+ (NSDictionary *)emoticonAndroid_iOSDic {
    static NSDictionary *dict;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *emoticonBundlePath = [[NSBundle mainBundle] pathForResource:@"GDHCKBFacePanelResources" ofType:@"bundle"];
        dict = [NSDictionary dictionaryWithContentsOfFile:[emoticonBundlePath stringByAppendingPathComponent:@"GDHfaceAndroid_iOS.plist"]];
    });
    return dict;
}


/// 表情字典 key-value ： [吃惊]:表情地址
+ (NSDictionary *)emoticonDic {
    static NSMutableDictionary *dic;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *emoticonBundlePath = [[NSBundle mainBundle] pathForResource:@"GDHCKBFacePanelResources" ofType:@"bundle"];
        dic = [self _emoticonDicFromPath:emoticonBundlePath name:@"GDHfaceFz.plist"];
    });
    return dic;
}

/// 表情图片路劲
+ (NSMutableDictionary *)_emoticonDicFromPath:(NSString *)path name:(NSString *)name {
    NSMutableDictionary *dict = [NSMutableDictionary new];
    
    NSString *plistPath = [path stringByAppendingPathComponent:name];//GDHface.plist
    NSDictionary *plist = [NSDictionary dictionaryWithContentsOfFile:plistPath];
    if (plist) {
        NSArray * allKeys = plist.allKeys;
        for (int i = 0; i<allKeys.count; i++) {
            NSString * key = allKeys[i];
            dict[key] = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",plist[key]]];
        }
    }    
    return dict;
}

/// 朋友圈表情缓存
+ (YYMemoryCache *)imageCache {
    static YYMemoryCache *cache;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        cache = [YYMemoryCache new];
        cache.shouldRemoveAllObjectsOnMemoryWarning = NO;
        cache.shouldRemoveAllObjectsWhenEnteringBackground = NO;
        cache.name = @"WeChatMomentsCache";
    });
    return cache;
}

+ (UIImage *)imageWithPath:(NSString *)path {
    if (!path) return nil;
    UIImage *image = [[self imageCache] objectForKey:path];
    if (image) return image;
    if (path.pathScale == 1) {
        // 查找 @2x @3x 的图片
        NSArray *scales = [NSBundle preferredScales];
        for (NSNumber *scale in scales) {
            image = [UIImage imageWithContentsOfFile:[path stringByAppendingPathScale:scale.floatValue]];
            if (image) break;
        }
    } else {
        image = [UIImage imageWithContentsOfFile:path];
    }
    if (image) {
        image = [image yy_imageByDecoded];
        [[self imageCache] setObject:image forKey:path];
    }
    return image;
}


@end
